package org.xx.armory.web.tags;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.jsp.JspException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

public final class ACss extends BaseTagHandler {
    public static final String DEFAULT_PROPOSAL = "default";
    private static final long serialVersionUID = 1L;
    private static final Charset DEFAULT_CHARSET;
    private static final String CSS_PATH = "css";

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
    }

    private String proposal = "default";

    public ACss() {
    }

    public final String getPro() {
        return this.proposal;
    }

    public final void setPro(String value) {
        value = StringUtils.trimToEmpty(value);
        this.proposal = value.isEmpty() ? "default" : value;
    }

    public int doStartTag()
            throws JspException {
        super.doStartTag();
        this.getRenderer().comment("CSS goes here");
        String profile = TagUtils.evalThemeUrl(this.pageContext, CSS_PATH, this.getPro() + ".txt");

        final List<String> lines;
        try (final InputStream ins = this.getStaticResourceAsStream(profile)) {
            lines = IOUtils.readLines(ins, DEFAULT_CHARSET);
        } catch (IOException ex) {
            throw new JspException(ex);
        }

        for (final String line : lines) {
            if (line != null && !line.isEmpty()) {
                this.getRenderer().newline();
                this.getRenderer().setAttribute("rel", "stylesheet");
                this.getRenderer().setAttribute("type", "text/css");
                this.getRenderer().setAttribute("href", TagUtils.evalRelThemeUrl(this.pageContext, CSS_PATH, line));
                this.getRenderer().startTag("link");
                this.getRenderer().endTag();
            }
        }

        return 0;
    }
}

